import jdk.internal.org.objectweb.asm.ClassReader;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: AliceMana
 * Date: 2022-09-26
 * Time: 19:47
 */
public class Test {
  public class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {

      }
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }

    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if (root==null && subRoot!=null || root!=null && subRoot==null) {
            return false;
        }
        if (root==null || subRoot==null) {
            return false;
        }
        //1、判断两棵树 是不是两颗相同的树
        if (isSameTree(root, subRoot)) {
            return true;
        }
        //2、subRoot是不是 root.left 子树
        if (isSubtree(root.left, subRoot)) {
            return true;
        }
        //3、subRoot是不是 root.right 子树
        return isSubtree(root.right, subRoot);
    }
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p == null && q != null  || p != null && q == null ) {
            return false;
        }
        if(p == null && q == null) {
            return true;
        }
        if(p.val != q.val) {
            return false;
        }
        return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }

    public TreeNode invertTree(TreeNode root) {
      if (root == null) {
          return null;
      }
      TreeNode tmp = root.left;
      root.left = root.right;
      root.right = tmp;
      invertTree(root.left);
      invertTree(root.right);
      return root;
    }

    public boolean isSymmetric(TreeNode root) {
      if(root == null) {
          return true;
      }

      return isSymmetricChild(root.left,root.right);
    }

    private boolean isSymmetricChild(TreeNode leftTree,TreeNode rightTree) {
        if (leftTree == null&&rightTree != null || rightTree == null && leftTree != null) {
            return false;
        }
        if (leftTree == null && rightTree == null) {
            return true;
        }
        if (leftTree.val != rightTree.val) {
            return false;
        }
        return isSymmetricChild(leftTree.left, rightTree.right) && isSymmetricChild(leftTree.right, rightTree.left);
    }
}
